﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.RoleMenuCommand;
using B.S.BaseData.Read.API.DTO;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.RoleMenuHandler
{
    /// <summary>
    /// 查询菜单树状命令处理类
    /// </summary>
    public class QueryRoleMenuHandler : IRequestHandler<QueryRoleMenuCommand, APIResult<List<RoleMenuDTO>>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="menuRep"></param>
        /// <param name="mapper"></param>
        public QueryRoleMenuHandler(IBaseRepository<Menu> menuRep,IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }

        /// <summary>
        /// 方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<RoleMenuDTO>>> Handle(QueryRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<RoleMenuDTO>> result = new APIResult<List<RoleMenuDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = "查询菜单树状结构成功";
            result.Data = GetTree(0);
            return Task.FromResult(result);
        }

       public List<RoleMenuDTO> GetTree(int pid)
        {
            var list = menuRep.GetAll().Where(x => x.PId == pid && !x.IsDeleted).ToList();
            var res = new List<RoleMenuDTO>();
            foreach (var item in list)
            {
                var model = new RoleMenuDTO()
                {
                    value = item.MenuId,
                    label = item.MenuName,
                    children = GetTree(item.MenuId)

                };
                res.Add(model);
            }
            return res;
        }
    }
}
